package org.example.aienglishapp.service.article;

import org.example.aienglishapp.config.others.RedisService;
import org.example.aienglishapp.entity.article.Favorite;
import org.example.aienglishapp.mapper.article.FavoriteMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Transactional
@Service
public class FavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private RedisService redisService;

    // Redis缓存的前缀
    private static final String FAVORITE_KEY_PREFIX = "favorite:user:";

    // 用于格式化和解析 LocalDateTime 的格式
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_DATE_TIME;

    // 添加收藏
    public void addFavorite(Long userId, Long articleId) {
        // 存入数据库
        favoriteMapper.addFavorite(userId, articleId);

        // 存入 Redis，保存当前时间 (转为字符串)
        String redisKey = FAVORITE_KEY_PREFIX + userId;
        String currentTime = LocalDateTime.now().format(DATE_TIME_FORMATTER);  // 转为 ISO 格式字符串
        redisService.set(redisKey + ":article:" + articleId, currentTime);

        // 更新 Redis 缓存中的文章列表
        updateFavoritesInCache(userId);
    }

    // 删除收藏
    public void removeFavorite(Long userId, Long articleId) {
        // 从数据库删除收藏
        favoriteMapper.removeFavorite(userId, articleId);

        // 从 Redis 删除缓存
        redisService.delete(FAVORITE_KEY_PREFIX + userId + ":article:" + articleId);

        // 更新 Redis 缓存中的文章列表
        updateFavoritesInCache(userId);
    }

    // 获取用户所有收藏
    public List<Favorite> getAllFavoritesByUserId(Long userId) {
        // 从 Redis 获取收藏数据
        String redisKey = FAVORITE_KEY_PREFIX + userId;
        Object redisData = redisService.get(redisKey);

        if (redisData == null) {
            // 如果 Redis 没有数据，从数据库中获取
            List<Favorite> favorites = favoriteMapper.getAllFavoritesByUserId(userId);

            // 将数据库查询到的收藏信息存入 Redis
            List<Long> articleIdsFromDb = favorites.stream()
                    .map(Favorite::getArticleId)  // 获取 articleId
                    .collect(Collectors.toList());
            redisService.set(redisKey, articleIdsFromDb); // 存储 articleIds 列表

            return favorites;
        }

        // 如果 Redis 中有收藏数据，处理并返回
        List<Long> articleIds = (List<Long>) redisData;

        return articleIds.stream()
                .map(articleId -> new Favorite(userId, articleId)) // 根据 userId 和 articleId 创建 Favorite 对象
                .collect(Collectors.toList());
    }

    // 判断用户是否已收藏该文章
    public boolean isFavorited(Long userId, Long articleId) {
        // 先尝试从 Redis 获取收藏数据
        String redisKey = FAVORITE_KEY_PREFIX + userId;
        String cachedTimeStr = (String) redisService.get(redisKey + ":article:" + articleId);

        if (cachedTimeStr != null) {
            // 将字符串转换为 LocalDateTime
            LocalDateTime cachedTime = LocalDateTime.parse(cachedTimeStr, DATE_TIME_FORMATTER);
            return cachedTime != null;  // 如果 Redis 中有时间戳，说明已收藏
        }

        // 如果缓存中没有，查询数据库
        Favorite favorite = favoriteMapper.getFavoriteByUserIdAndArticleId(userId, articleId);
        return favorite != null;
    }

    // 根据 ID 获取收藏
    public Favorite getFavoriteById(Long favoriteId) {
        return favoriteMapper.getFavoriteById(favoriteId);
    }

    // 更新缓存中的所有收藏文章列表
    private void updateFavoritesInCache(Long userId) {
        // 从数据库获取所有收藏的文章ID
        List<Long> articleIdsFromDb = favoriteMapper.getAllFavoritesByUserId(userId).stream()
                .map(Favorite::getArticleId)
                .collect(Collectors.toList());

        // 更新 Redis 中的文章列表缓存
        String redisKey = FAVORITE_KEY_PREFIX + userId;
        redisService.set(redisKey, articleIdsFromDb);
    }
}